package com.zxc.gulimall.auth.web;

import com.alibaba.fastjson.TypeReference;
import com.zxc.common.constant.AuthServerConstant;
import com.zxc.common.utils.R;
import com.zxc.common.vo.MemberRespVo;
import com.zxc.gulimall.auth.vo.UserLoginVo;
import com.zxc.gulimall.auth.feign.MemberFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class LoginController {

    /*
    * 使用SpringMVC提供的ViewController（视图控制器）将请求页面映射过来。
    * */

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping(value = "/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null){
            //没登录
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }
    }

    @PostMapping(value = "/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程登录，重定向
        R login = memberFeignService.login(vo);

        if (login.getCode() == 0){
            //登录成功
            MemberRespVo data = login.getData("data",new TypeReference<MemberRespVo>(){});
            log.info("登录成功：用户信息：{}",data.toString());

            //1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
            //以后浏览器访问哪个网站就会带上这个网站的cookie
            //TODO 1、默认发的令牌。当前域（解决子域session共享问题）
            //TODO 2、使用JSON的序列化方式来序列化对象到Redis中
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }else {
            //登录失败
            Map<String,String> map = new HashMap<>();
            map.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }


}
